package com.video.client.manager;

import jakarta.websocket.Session;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.video.client.bean.User;

/**
 * websocket管理
 */
public class SocketManager {

	private static Logger log = LoggerFactory.getLogger(SocketManager.class);

	/**
	 * 客户端连接session集合 <id,Session></>
	 */
	private static Map<String, User> sessionMap = new ConcurrentHashMap<String, User>();

	/**
	 * 存放新加入的session 便于以后对session管理
	 * 
	 * @param userId  用户id
	 * @param session 用户session
	 */
	public synchronized static void setSession(String userId, Session session) {
		sessionMap.put(userId, new User(userId, "user:" + userId, session));
	}

	/**
	 * 根据session ID移除session
	 * 
	 * @param sessionId
	 */
	public static void removeSession(String sessionId) {
		if (null == sessionId) {
			return;
		}
		sessionMap.forEach((k, v) -> {
			if (sessionId.equals(v.getId())) {
				sessionMap.remove(k);
			}
		});
	}

	/**
	 * 给用户发送消息
	 * 
	 * @param userId  用户id
	 * @param message 消息
	 */
	public static void sendMessage(String userId, String message) {
		log.info("给用户发送消息,{},{}", userId, message);
		var session = sessionMap.get(userId).getSession();
		if (session != null) {
			synchronized (session) {
				try {
					session.getBasicRemote().sendText(message);
				} catch (IOException e) {
					log.info("发送websocket消息是异常,{}", e);
				}
			}
		}
	}
	
	/**
	 * 获取所用在线用户列表
	 * 
	 * @return
	 */
	public static List<User> getUserList(){
		return sessionMap.values().stream().collect(Collectors.toList());
	}

}